package com.example.clxy.service.impl;

import com.example.clxy.dao.UnbindMapper;
import com.example.clxy.dao.UserMapper;
import com.example.clxy.entity.Unbind;
import com.example.clxy.entity.User;
import com.example.clxy.entity.dto.UnBindDto;
import com.example.clxy.result.PageResult;
import com.example.clxy.result.WebRestResult;
import com.example.clxy.result.business.PageResult.UnbindPageResult;
import com.example.clxy.service.SendMailService;
import com.example.clxy.service.WechatBindService;
import com.example.clxy.util.HttpUtils;
import com.example.clxy.util.RespUtil;
import com.example.clxy.util.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author weichong
 * date 2020-08-06
 * @Description:
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class WechatBindServiceImpl implements WechatBindService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UnbindMapper unbindMapper;
    @Autowired
    private SendMailService sendMailService;

    @Override
    public WebRestResult addWechatBind(String openid, String account, String wxnumber, String wxname) {
        if (account == null || account.isEmpty() || openid == null || openid.isEmpty()) {
            return RespUtil.failResp("openid和用户账号不能为空");
        }
        User user = userMapper.getUserByAccount(account);
        if (user == null) {
            return RespUtil.failResp("账号不存在");
        }
        if (user.getOpenid() != null && !user.getOpenid().isEmpty()) {
            return RespUtil.failResp("该用户已绑定微信");
        }
        user.setOpenid(openid);
        user.setWxname(wxname);
        user.setWxnumber(wxnumber);
        if (userMapper.updateByPrimaryKeySelective(user) == 1) {
            return RespUtil.successResp("绑定微信成功");
        }
        return RespUtil.failResp("绑定微信失败");
    }

    @Override
    public WebRestResult addWechatBindApply(Unbind unbind) {

        if (StringUtils.isBlank(unbind.getWxname())) return RespUtil.failResp("申请人微信名不能为空");
        if (StringUtils.isBlank(unbind.getWxnumber())) return RespUtil.failResp("申请人微信号不能为空");
        if (StringUtils.isBlank(unbind.getAccount())) return RespUtil.failResp("申请解绑账号不能为空");
        if (StringUtils.isBlank(unbind.getUnbindemail())) return RespUtil.failResp("接收解绑结果邮箱不能为空");

        Unbind unbind2 = unbindMapper.selectByAccount(unbind.getAccount());
        if (unbind2 != null) {
            return RespUtil.failResp("请不要重复申请");
        }
        unbind.setUnbindid(UUIDUtil.randomUUID());

        unbind.setFlag("0");
        unbind.setCreatedTime(new Date());
        unbind.setUpdatedTime(new Date());

        if (unbindMapper.insert(unbind) == 1) {
            return RespUtil.successResp("申请成功");
        }
        return RespUtil.failResp("申请失败");
    }

    @Override
    public PageResult<UnbindPageResult> getWechatBindApply(int page, int pagesize) {
        PageResult<UnbindPageResult> res = new PageResult<>();
        int begin = (page - 1) * pagesize;
        int end = pagesize;
        List<UnbindPageResult> unbindList = unbindMapper.getWechatBindApply(begin, end, pagesize);
        if (unbindList.size() > 0) {
            res.setTotal(unbindList.get(0).getCnt());
            res.setPageCount(unbindList.get(0).getPage());
            res.setRows(unbindList);
        }
        res.setResult(WebRestResult.SUCCESS);
        res.setMessage("查询所有解绑申请成功成功");
        return res;

    }

    @Override
    public WebRestResult passWechatBindApply(String unbindid) {
        if (StringUtils.isBlank(unbindid)) return RespUtil.failResp("解绑id不能为空");
        Unbind unbind = unbindMapper.selectByPrimaryKey(unbindid);
        if (unbind == null || unbind.getFlag().equals("1")) {
            return RespUtil.failResp("解绑申请不存在");
        }
        User user = userMapper.getUserByAccount(unbind.getAccount());
        if (user == null) {
            sendFailMail(unbind, "用户不存在");
            return RespUtil.failResp("解绑失败,用户不存在");
        }
        user.setOpenid("");
        user.setWxnumber("");
        user.setWxname("");
        if (userMapper.updateByPrimaryKeySelective(user) == 1) {
            unbind.setFlag("1");
            unbindMapper.updateByPrimaryKeySelective(unbind);
            sendSucccessMail(unbind);
            return RespUtil.successResp("解绑成功");
        }
        sendFailMail(unbind, null);
        return RespUtil.failResp("解绑失败");
    }

    @Override
    public WebRestResult refuseWechatBindApply(String unbindid, String rejectreason) {
        if (StringUtils.isBlank(unbindid)) return RespUtil.failResp("解绑id不能为空");
        Unbind unbind = unbindMapper.selectByPrimaryKey(unbindid);
        if (unbind == null) {
            return RespUtil.failResp("解绑申请不存在");
        }
        sendFailMail(unbind, rejectreason);
        unbind.setRejectreason(rejectreason);
        unbind.setFlag("1");
        if (unbindMapper.updateByPrimaryKeySelective(unbind) == 1) {
            return RespUtil.successResp("拒绝解绑成功");
        }
        return RespUtil.failResp("解绑失败");

    }


    public void sendSucccessMail(Unbind unbind) {
        sendMailService.sendSimpleMail(unbind.getUnbindemail(), "材料学院实验系统,账号微信解绑通知", "账号:" + unbind.getAccount() + "成功解绑微信,请您尽快绑定");
    }

    public void sendFailMail(Unbind unbind, String rejectreason) {
        String msg = "账号:" + unbind.getAccount() + "解绑微信失败";
        if (!StringUtils.isBlank(rejectreason)) {
            msg += ",管理员拒绝理由:" + rejectreason + "";
        }
        msg += ",请再次申请或联系学院系统管理员";
        sendMailService.sendSimpleMail(unbind.getUnbindemail(), "材料学院实验系统,账号微信解绑通知", msg);
    }

    @Override
    public WebRestResult wxApplyUnbind(UnBindDto unBindDto) {
        WebRestResult result = new WebRestResult();
        Unbind unbind = new Unbind();
        User userByAccount = userMapper.getUserByAccount(unBindDto.getAccount());
        if (userByAccount == null) {
            result.setResult(WebRestResult.FAILURE);
            result.setMessage("该申请解绑的工号在系统中不存在！！");
        }
        if (unBindDto.getEmail() == null || "".equals(unBindDto.getEmail())
                || unBindDto.getAccount() == null || "".equals(unBindDto.getAccount())
                || unBindDto.getApplyreason() == null || "".equals(unBindDto.getApplyreason())) {
            result.setMessage("请将工号、邮箱地址、申请理由填写完整");
            result.setResult(WebRestResult.FAILURE);
            return result;
        }
        unbind.setApplyreason(unBindDto.getApplyreason());
        unbind.setAccount(unBindDto.getAccount());
        unbind.setUnbindemail(unBindDto.getEmail());
        unbind.setWxname(unBindDto.getNickname());
        unbind.setFlag("0");
        unbind.setCreatedTime(new Date());
        unbind.setUpdatedTime(new Date());
        unbind.setUnbindid(UUIDUtil.randomUUID());
        if (unbindMapper.insertSelective(unbind) == 1) {
            result.setResult(WebRestResult.SUCCESS);
            result.setMessage("申请解绑操作成功提交！");
        } else {
            result.setResult(WebRestResult.FAILURE);
            result.setMessage("申请解绑操作提交失败！");
        }
        return result;
    }



}
